--channel create event hook
--author huronuan@hongboict.com

freeswitch.consoleLog("info","channel create !\n")

trunk_id = event:getHeader("variable_trunk")
direction = event:getHeader("variable_direction")

json = require "json"
api = freeswitch.API()

function getHashData( name )
	return api:executeString("hash select/realm/" .. name)
end

function setHashData( name, val )
	api:executeString("hash insert/realm/" .. name .. "/" .. val);
	freeswitch.consoleLog("info", "create.lua set hash key " .. name .. "/" .. val .. "\n");
end
function setTrunkCallCount(trunk_calls) 
	local call_in_count = 0
	local call_out_count = 0;
	local temp = {};

	for k,v in pairs(trunk_calls) do
		if api:executeString("uuid_exists " .. v.uuid) == "false" then
			freeswitch.consoleLog("info","uuid not exists " ..v.uuid)
			table.insert(temp,v)
		end
	end

	for k,v in pairs(temp) do
		for k1,v1 in pairs(trunk_calls) do
			if v.uuid == v1.uuid then
				table.remove(trunk_calls,k1)
				break
			end
		end
	end

	for k,v in pairs(trunk_calls) do
		if v.direction == "inbound" then
			call_in_count = call_in_count + 1
		else
			call_out_count = call_out_count +1
		end
	end
	setHashData(trunk_id.."_call_in_count",call_in_count)
	setHashData(trunk_id.."_call_out_count",call_out_count)
	return trunk_calls
end

if trunk_id ~= nil and trunk_id ~= "" and direction == "outbound"  then
	
	-- call out cache 
	local trunk_calls = {}
	local trunk_calls_json = getHashData(trunk_id)
	if trunk_calls_json ~= nil and trunk_calls_json~= "" then
		freeswitch.consoleLog("INFO","get trunk call :" .. trunk_calls_json .. "\n")
		trunk_calls = json.decode(trunk_calls_json)
	end

	local channel = {}
	channel.uuid = event:getHeader("variable_uuid")
	channel.name = event:getHeader("variable_channel_name")
	channel.caller_id_number = event:getHeader("Caller-Caller-ID-Number")
	channel.destination_number = event:getHeader("Caller-Destination-Number")
	channel.direction = event:getHeader("variable_direction")
	channel.create_at = event:getHeader("Event-Date-Local")

	table.insert(trunk_calls,channel)
	trunk_calls = setTrunkCallCount(trunk_calls)
	setHashData( trunk_id,json.encode(trunk_calls) )

end

